﻿using Google.Protobuf.WellKnownTypes;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Asn1.Tsp;
using Org.BouncyCastle.Asn1.X9;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using static log4net.Appender.RollingFileAppender;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;

namespace CloudApiServer.Controllers
{
    /// <summary>
    /// 国标处方中心接口控制器.
    /// </summary>
    [RoutePrefix("epc/api")]
    public class FsiEpcController : ApiController
    {


        /*接口*/
        /// <summary>
        /// 医保接口没找到的统一接口返回
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public IHttpActionResult FsiNotFound(HttpRequestMessage request)
        {
            string url = request.RequestUri.ToString();
            string Method = request.Method.ToString();
            string Errnum = LogHelper.GetErrornumber();
            try
            {
                FsiEpcHeader FsiHeader = new FsiEpcHeader
                {
                    code = 50000,
                    appId = FsiEpcTokeninfo.appId,
                    message =  $"[{Errnum}]调用自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加,当前请求入参：" + request.Content.ReadAsStringAsync().Result,
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                {
                    code = 50000,
                    message = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：" + ex.Message
                };
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 电子处方线下流转授权
        /// </summary>
        /// <returns></returns>
        [Route("agentReqRxAuthReg")]
        [HttpPost]
        public async Task<IHttpActionResult> agentReqRxAuthReg(HttpRequestMessage request)
        {
            DataTable dt = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiEpcApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }

                    Console.WriteLine("处方中心入参：" + request.Content.ReadAsStringAsync().Result);
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                    string encData = fsiRequest.encData;
                    string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    string version = fsiRequest.version;
                    string timestamp = fsiRequest.timestamp.ToString();
                    Console.WriteLine("处方中心入参解密：" + decData);

                    var AgentReqRxAuthRegInput = JsonConvert.DeserializeObject<FsiRequestEpcAgentReqRxAuthRegInput>(decData);

                    if (string.IsNullOrEmpty(AgentReqRxAuthRegInput.certno) 
                        || string.IsNullOrEmpty(AgentReqRxAuthRegInput.psnName) ||string.IsNullOrEmpty(AgentReqRxAuthRegInput.fixmedinsCode)
                        ||string.IsNullOrEmpty(AgentReqRxAuthRegInput.regerName) ||string.IsNullOrEmpty(AgentReqRxAuthRegInput.regerCertType)
                        ||string.IsNullOrEmpty(AgentReqRxAuthRegInput.regerCertno) || string.IsNullOrEmpty(AgentReqRxAuthRegInput.ipInfo)
                        ||string.IsNullOrEmpty(AgentReqRxAuthRegInput.psnCertType))
                    {
                        throw new Exception("参数校验失败：必填项字段校验失败，certno、psnName、psnCertType、fixmedinsCode、regerName、regerCertno、regerCertType、ipInfo字段不能为空！当前入参：" + decData);
                    }

                    var AgentReqRxAuthRegOutput = new FsiEpcAgentReqRxAuthRegOutputData
                    {
                        regSn = Guid.NewGuid().ToString(),
                        datetime = DateTime.Now
                    };
                    /*出参加密*/
                    string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(AgentReqRxAuthRegOutput, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    /*加密结束*/
                    FsiEpcOutput<FsiEpcAgentReqRxAuthRegOutputData> signDto = new FsiEpcOutput<FsiEpcAgentReqRxAuthRegOutputData>
                    {
                        appId = FsiEpcTokeninfo.appId,
                        encType = "SM4",
                        signType = "SM2",
                        timestamp = fsiRequest.timestamp.ToString(),
                        data = AgentReqRxAuthRegOutput,
                        version = version,
                        key = FsiEpcTokeninfo.appSecret,

                    };
                    Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(AgentReqRxAuthRegOutput, Formatting.None));
                    Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                    //签名
                    string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                    /*---------------解密部分-----------------*/
                    string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    Console.WriteLine("解密：" + eeee);
                    Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                    Console.WriteLine("验签：" + isVerify);
                    FsiEpcHeader FsiHeader = new FsiEpcHeader
                    {
                        code = 0,
                        appId = FsiEpcTokeninfo.appId,
                        encData = returnEncData,
                        signData = signData,
                        message = "success",
                        timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                    };
                    return Json(FsiHeader);
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                    {
                        code = 50000,
                        message = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：" + ex.Message,
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }


        /// <summary>
        /// 电子处方线下流转授权
        /// </summary>
        /// <returns></returns>
        [Route("fixmedins/rxAuthQuery")]
        [HttpPost]
        public async Task<IHttpActionResult> rxAuthQuery(HttpRequestMessage request)
        {
            DataTable dt = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiEpcApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }

                    Console.WriteLine("处方中心入参："+ request.Content.ReadAsStringAsync().Result);
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                    string encData = fsiRequest.encData;
                    string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    string version = fsiRequest.version;
                    string timestamp = fsiRequest.timestamp.ToString();
                    Console.WriteLine("处方中心入参解密：" + decData);

                    var RxAuthQueryInput = JsonConvert.DeserializeObject<FsiRequestEpcRxAuthQueryInput>(decData);
                    string certno = RxAuthQueryInput.certno;
                    string psnName = RxAuthQueryInput.psnName;

                    string ecToken = RxAuthQueryInput.ecToken;
                    string regSn = RxAuthQueryInput.regSn;
                    if(!string.IsNullOrEmpty(ecToken) && !string.IsNullOrEmpty(regSn))
                    {
                        throw new Exception("参数校验失败：传入的患者电子凭证token和人工审核登记流水号不能同时有值，两者只能选一个传值！当前入参：" + decData);
                    }


                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_prescription where certno=@certno";
                        cmd.Parameters.AddWithValue("@certno", certno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            List<FsiEpcRxAuthQueryOutputData> RxAuthQueryOutputData = new List<FsiEpcRxAuthQueryOutputData>();
                            foreach (DataRow row in dt.Rows)
                            {
                                FsiEpcRxAuthQueryOutputData item = new FsiEpcRxAuthQueryOutputData
                                {
                                    authRxno = row["auth_rxno"].ToString(),
                                    epcToken = row["epc_token"].ToString(),
                                    expiresIn = row["expires_in"].ToString(),
                                    fixmedinsCode = row["fixmedins_code"].ToString(),
                                    fixmedinsName = row["fixmedins_name"].ToString(),
                                    prscTime = row["prsc_time"].ToString(),
                                    diseCodg = row["dise_codg"].ToString(),
                                    diseName = row["dise_name"].ToString(),
                                    valiEndTime = row["valid_end_time"].ToString()
                                };
                                RxAuthQueryOutputData.Add(item);
                            }
                            /*出参加密*/
                            string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(RxAuthQueryOutputData, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                            /*加密结束*/
                            FsiEpcOutputList<FsiEpcRxAuthQueryOutputData> signDto = new FsiEpcOutputList<FsiEpcRxAuthQueryOutputData>
                            {
                                appId = FsiEpcTokeninfo.appId,
                                encType = "SM4",
                                signType = "SM2",
                                timestamp = fsiRequest.timestamp.ToString(),
                                data = RxAuthQueryOutputData,
                                version = version,
                                key = FsiEpcTokeninfo.appSecret,

                            };
                            Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(RxAuthQueryOutputData, Formatting.None));
                            Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                            //签名
                            string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                            /*---------------解密部分-----------------*/
                            string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                            Console.WriteLine("解密：" + eeee);
                            Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                            Console.WriteLine("验签：" + isVerify);
                            FsiEpcHeader FsiHeader = new FsiEpcHeader
                            {
                                code = 0,
                                appId = FsiEpcTokeninfo.appId,
                                encData = returnEncData,
                                signData = signData,
                                message = "success",
                                timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                            };
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                    {
                        code = 50000,
                        message = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：" + ex.Message,
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 电子处方下载
        /// </summary>
        /// <returns></returns>
        [Route("fixmedins/rxInfoDld")]
        [HttpPost]
        public async Task<IHttpActionResult> rxInfoDld(HttpRequestMessage request)
        {
            DataTable dtinfo = new DataTable();
            DataTable dtdetail = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiEpcApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    Console.WriteLine("处方中心入参：" + request.Content.ReadAsStringAsync().Result);
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                    string encData = fsiRequest.encData;
                    string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    Console.WriteLine("处方中心入参解密：" + decData);

                    var RxInfoDldInput = JsonConvert.DeserializeObject<FsiRequestEpcRxInfoDldInput>(decData);
                    string authRxno = RxInfoDldInput.authRxno;
                    string epcToken = RxInfoDldInput.epcToken;

                    if (string.IsNullOrEmpty(authRxno) || string.IsNullOrEmpty(epcToken))
                    {
                        throw new Exception("参数校验失败：传入的电子处方令牌|医保处方授权编号为空，请检查入参！当前入参：" + decData);
                    }
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_prescription where  epc_token=@epc_token and auth_rxno=@auth_rxno";
                        cmd.Parameters.AddWithValue("@epc_token", epcToken);
                        cmd.Parameters.AddWithValue("@auth_rxno", authRxno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dtinfo.Load(reader);
                            if (dtinfo.Rows.Count == 0)
                            {
                                throw new Exception($"查询处方列表失败！处方授权编号：{authRxno} 未查询到处方列表，如需测试请联系管理员增加相关数据！");
                            }
                            cmd.Parameters.Clear();
                        }
                        cmd.CommandText = "select * from fsi_prescription_detail where   auth_rxno=@auth_rxno";
                        cmd.Parameters.AddWithValue("@auth_rxno", authRxno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            List<FsiEpcRxInfoDldOutputRxDetlList> dataList = new List<FsiEpcRxInfoDldOutputRxDetlList>();
                            dtdetail.Load(reader);
                            cmd.Parameters.Clear();
                            if (dtdetail.Rows.Count != 0)
                            {
                                foreach (DataRow row in dtdetail.Rows)
                                {
                                    FsiEpcRxInfoDldOutputRxDetlList item = new FsiEpcRxInfoDldOutputRxDetlList
                                    {
                                        medListCodg = row["med_list_codg"].ToString(),
                                        fixmedinsHilistId = row["fixmedins_hilist_id"].ToString(),
                                        hospPrepFlag = row["hosp_prep_flag"].ToString(),
                                        rxItemTypeCode = row["rx_item_type_code"].ToString(),
                                        rxItemTypeName = row["rx_item_type_name"].ToString(),
                                        tcmdrugTypeCode = row["tcmdrug_type_code"].ToString(),
                                        tcmdrugTypeName = row["tcmdrug_type_name"].ToString(),
                                        tcmherbFoote = row["tcmherb_foote"].ToString(),
                                        mednTypeCode = row["medn_type_code"].ToString(),
                                        mednTypeName = row["medn_type_name"].ToString(),
                                        mainMedcFlag = row["main_medc_flag"].ToString(),
                                        urgtFlag = row["urgt_flag"].ToString(),
                                        basMednFlag = row["bas_medn_flag"].ToString(),
                                        impDrugFlag = row["imp_drug_flag"].ToString(),
                                        drugProdname = row["drug_prodname"].ToString(),
                                        drugGenname = row["drug_genname"].ToString(),
                                        drugDosform = row["drug_dosform"].ToString(),
                                        drugSpec = row["drug_spec"].ToString(),
                                        prdrName = row["prdr_name"].ToString(),
                                        drugCnt = Convert.ToDecimal(row["drug_cnt"]),
                                        medcWayCodg = row["medc_way_codg"].ToString(),
                                        medcWayDscr = row["medc_way_dscr"].ToString(),
                                        medcEndtime = row["medc_endtime"].ToString(),
                                        medcBegntime = row["medc_begntime"].ToString(),
                                        medcDays = Convert.ToDecimal(row["medc_days"]),
                                        drugDosunt = row["drug_dosunt"].ToString(),
                                        sinDoscnt = Convert.ToDecimal(row["sin_doscnt"]),
                                        sinDosunt = row["sin_dosunt"].ToString(),
                                        usedFrquCodg = row["used_frqu_codg"].ToString(),
                                        usedFrquName = row["used_frqu_name"].ToString(),
                                        drugTotlcnt = row["drug_totlcnt"].ToString(),
                                        drugTotlcntEmp = row["drug_totlnt_emp"].ToString(),
                                        hospApprFlag = row["hosp_appr_flag"].ToString()
                                    };
                                    dataList.Add(item);
                                }
                                var RxInfoDldOutputData = new FsiEpcRxInfoDldOutputData
                                {
                                    hiRxno = dtinfo.Rows[0]["hi_rxno"].ToString(),
                                    fixmedinsCode = dtinfo.Rows[0]["fixmedins_code"].ToString(),
                                    fixmedinsName = dtinfo.Rows[0]["fixmedins_name"].ToString(),
                                    prscTime = dtinfo.Rows[0]["prsc_time"].ToString(),
                                    rxFile = dtinfo.Rows[0]["rx_file"].ToString(),
                                    rxTraceCode = dtinfo.Rows[0]["rx_trace_code"].ToString(),
                                    prscDeptName = dtinfo.Rows[0]["prsc_dept_name"].ToString(),
                                    rxTypeCode = dtinfo.Rows[0]["rx_type_code"].ToString(),
                                    rxTypeName = dtinfo.Rows[0]["rx_type_name"].ToString(),
                                    longRxFlag = dtinfo.Rows[0]["long_rx_flag"].ToString(),
                                    fileSuffix = dtinfo.Rows[0]["file_suffix"].ToString(),
                                    valiEndTime = dtinfo.Rows[0]["valid_end_time"].ToString(),
                                    rxDetlList = dataList,
                                    rxOtpinfo = new FsiEpcRxInfoDldOutputRxOtpinfo
                                    {
                                        medType = dtinfo.Rows[0]["med_type"].ToString(),
                                        patnName = dtinfo.Rows[0]["patn_name"].ToString(),
                                        //patnAge = Convert.ToDecimal(dtinfo.Rows[0]["patn_age"]),
                                        patnHgt = dtinfo.Rows[0]["patn_hgt"].ToString(),
                                        //patnWt = Convert.ToDecimal(dtinfo.Rows[0]["patn_wt"]),
                                        gend = dtinfo.Rows[0]["gend"].ToString(),
                                        //geso_val = Convert.ToDecimal(dtinfo.Rows[0]["geso_val"]),
                                        nwbFlag = dtinfo.Rows[0]["nwb_flag"].ToString(),
                                        nwbAge = dtinfo.Rows[0]["nwb_age"].ToString(),
                                        //suck_prd_flag = (int)dtinfo.Rows[0]["suck_prd_flag"],
                                        algsHis = dtinfo.Rows[0]["algs_his"].ToString(),
                                        diseCodg = dtinfo.Rows[0]["dise_codg"].ToString(),
                                        diseName = dtinfo.Rows[0]["dise_name"].ToString(),
                                        otpIptFlag = dtinfo.Rows[0]["otp_ipt_flag"].ToString(),
                                        maindiagCode = dtinfo.Rows[0]["main_diag_code"].ToString(),
                                        maindiagName = dtinfo.Rows[0]["main_diag_name"].ToString(),
                                        diseCondDscr = dtinfo.Rows[0]["dise_cond_dscr"].ToString()
                                    }

                                };

                                /*出参加密*/
                                string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(RxInfoDldOutputData, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                                /*加密结束*/
                                FsiEpcOutput<FsiEpcRxInfoDldOutputData> signDto = new FsiEpcOutput<FsiEpcRxInfoDldOutputData>
                                {
                                    appId = FsiEpcTokeninfo.appId,
                                    encType = "SM4",
                                    signType = "SM2",
                                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString(),
                                    data = RxInfoDldOutputData
                                };
                                Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(RxInfoDldOutputData, Formatting.None));
                                Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                                //签名
                                string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                                ///*---------------解密部分-----------------*/
                                string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                                Console.WriteLine("解密：" + eeee);
                                Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                                Console.WriteLine("验签：" + isVerify);
                                FsiEpcHeader FsiHeader = new FsiEpcHeader
                                {
                                    code = 0,
                                    appId = FsiEpcTokeninfo.appId,
                                    encData = returnEncData,
                                    signData = signData,
                                    message = "success",
                                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                                };
                                return Json(FsiHeader);

                            }
                            else
                            {
                                throw new Exception($"查询处方明细列表失败！处方授权编号：{authRxno} 未查询到处方药品列表，如需测试请联系管理员增加相关数据！");
                            }

                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                    {
                        code = 50000,
                        message = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：" + ex.Message,
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 电子处方信息核验
        /// </summary>
        /// <returns></returns>
        [Route("fixmedins/rxInfoVerify")]
        [HttpPost]
        public  IHttpActionResult rxInfoVerify(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiEpcApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                Console.WriteLine("处方中心入参：" + request.Content.ReadAsStringAsync().Result);
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                string encData = fsiRequest.encData;
                string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                Console.WriteLine("处方中心入参解密：" + decData);

                var RxInfoVerifyOutputData = new FsiEpcRxInfoVerifyOutputData
                {
                    flag = true,
                    rxSignVerifySn = "rxSignVerifySn1234567890",
                    signCertDn = "signCertDn1234567890",
                    signCertSn = "signCertSn1234567890"
                };

                /*出参加密*/
                string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(RxInfoVerifyOutputData, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                /*加密结束*/
                FsiEpcOutput<FsiEpcRxInfoVerifyOutputData> signDto = new FsiEpcOutput<FsiEpcRxInfoVerifyOutputData>
                {
                    appId = FsiEpcTokeninfo.appId,
                    encType = "SM4",
                    signType = "SM2",
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString(),
                    data = RxInfoVerifyOutputData
                };
                Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(RxInfoVerifyOutputData, Formatting.None));
                Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                //签名
                string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                ///*---------------解密部分-----------------*/
                string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                Console.WriteLine("解密：" + eeee);
                Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                Console.WriteLine("验签：" + isVerify);
                FsiEpcHeader FsiHeader = new FsiEpcHeader
                {
                    code = 0,
                    appId = FsiEpcTokeninfo.appId,
                    encData = returnEncData,
                    signData = signData,
                    message = "success",
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                {
                    code = 50000,
                    message = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：" + ex.Message,
                };
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 电子处方审核信息上传
        /// </summary>
        /// <returns></returns>
        [Route("fixmedins/rxChkUpld")]
        [HttpPost]
        public IHttpActionResult rxChkUpld(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiEpcApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                Console.WriteLine("处方中心入参：" + request.Content.ReadAsStringAsync().Result);
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                string encData = fsiRequest.encData;
                string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                Console.WriteLine("处方中心入参解密：" + decData);

                var RxChkUpldOutputData = new FsiEpcRxChkUpldOutputData
                {
                    flag = true,
                    rxChkBizSn = "rxChkBizSn1234567890",
                };

                /*出参加密*/
                string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(RxChkUpldOutputData, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                /*加密结束*/
                FsiEpcOutput<FsiEpcRxChkUpldOutputData> signDto = new FsiEpcOutput<FsiEpcRxChkUpldOutputData>
                {
                    appId = FsiEpcTokeninfo.appId,
                    encType = "SM4",
                    signType = "SM2",
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString(),
                    data = RxChkUpldOutputData
                };
                Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(RxChkUpldOutputData, Formatting.None));
                Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                //签名
                string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                ///*---------------解密部分-----------------*/
                string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                Console.WriteLine("解密：" + eeee);
                Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                Console.WriteLine("验签：" + isVerify);
                FsiEpcHeader FsiHeader = new FsiEpcHeader
                {
                    code = 0,
                    appId = FsiEpcTokeninfo.appId,
                    encData = returnEncData,
                    signData = signData,
                    message = "success",
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                {
                    code = 50000,
                    message = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：" + ex.Message,
                };
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 药品销售出库明细上传
        /// </summary>
        /// <returns></returns>
        [Route("fixmedins/rxSelDrugUpld")]
        [HttpPost]
        public IHttpActionResult rxSelDrugUpld(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiEpcApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                Console.WriteLine("处方中心入参：" + request.Content.ReadAsStringAsync().Result);
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                string encData = fsiRequest.encData;
                string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                Console.WriteLine("处方中心入参解密：" + decData);

                var RxSelDrugUpldOutputData = new FsiEpcRxSelDrugUpldOutputData
                {
                    flag = true
                };

                /*出参加密*/
                string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(RxSelDrugUpldOutputData, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                /*加密结束*/
                FsiEpcOutput<FsiEpcRxSelDrugUpldOutputData> signDto = new FsiEpcOutput<FsiEpcRxSelDrugUpldOutputData>
                {
                    appId = FsiEpcTokeninfo.appId,
                    encType = "SM4",
                    signType = "SM2",
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString(),
                    data = RxSelDrugUpldOutputData
                };
                Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(RxSelDrugUpldOutputData, Formatting.None));
                Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                //签名
                string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                ///*---------------解密部分-----------------*/
                string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                Console.WriteLine("解密：" + eeee);
                Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                Console.WriteLine("验签：" + isVerify);
                FsiEpcHeader FsiHeader = new FsiEpcHeader
                {
                    code = 0,
                    appId = FsiEpcTokeninfo.appId,
                    encData = returnEncData,
                    signData = signData,
                    message = "success",
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                {
                    code = 50000,
                    message = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：" + ex.Message,
                };
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 处方中心解密测试接口
        /// </summary>
        /// <param name="request">test</param>
        /// <returns></returns>
        [Route("fixmedins/Test")]
        [HttpPost]
        public async Task<IHttpActionResult> Test(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiEpcApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    Console.WriteLine("处方中心入参：" + request.Content.ReadAsStringAsync().Result);
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                    string encData = fsiRequest.encData;
                    string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    Console.WriteLine("解密：" + decData);
                    return Ok(decData);

                }
                catch (Exception ex)
                {
                    return Json(ex);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
    }
}
